package api

import (
	"chatbot-api-go/domain/ai/models"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"io"
	"net/http"
	"strings"
)

type Ai interface {
	DoChatGPT(openAiKey string, question string) error
}

func DoChatGPT(openAiKey string, question string) (result string, err error) {
	aiUrl := fmt.Sprintf("https://api.openai.com/v1/completions")

	paramJson := "{\"model\": \"text-davinci-003\", \"prompt\": \"" + question + "\", \"temperature\": 0, \"max_tokens\": 1024}"

	req, _ := http.NewRequest("POST", aiUrl, strings.NewReader(paramJson))
	req.Header.Add("Authorization", "Bearer "+openAiKey)
	req.Header.Add("Content-Type", "application/json")

	response, err := http.DefaultClient.Do(req)

	if err != nil {
		zap.S().Errorw("【DoChatGPT】调用ChatGpt失败",
			"msg",
			err.Error(),
		)
	}
	body, err := io.ReadAll(response.Body)
	res := models.AIAnswer{}
	err = json.Unmarshal(body, &res)
	var builder strings.Builder
	for _, choice := range res.Choices {
		builder.WriteString(choice.Text)
	}

	return builder.String(), nil
}
